const { resolve } = require('path');
const { sync } = require('glob');
const { createCoverageMap } = require('istanbul-lib-coverage');
const { createContext } = require('istanbul-lib-report');
const { create } = require('istanbul-reports');

const coverageMap = createCoverageMap();

const coverageDir = resolve(__dirname, '../../coverage-frontend');
const e2eCoverageDir = resolve(__dirname, '../../coverage-e2e-frontend');

const reportFiles = sync(`${coverageDir}/*/coverage-final.json`);
const preMergedJestCoverage = sync(`${coverageDir}/coverage-final.json`);
const e2eCoverageFile = sync(`${e2eCoverageDir}/coverage-final.json`);

// Normalize coverage report generated by jest that has additional "data" key
// https://github.com/facebook/jest/issues/2418#issuecomment-423806659
const normalizeReport = (report) => {
  const normalizedReport = { ...report };
  Object.entries(normalizedReport).forEach(([k, v]) => {
    if (v.data) normalizedReport[k] = v.data;
  });
  return normalizedReport;
};

// Use individual jest-* coverage files if available, otherwise use pre-merged file
const jestCoverageFiles = reportFiles.length > 0 ? reportFiles : preMergedJestCoverage;

if (jestCoverageFiles.length > 0) {
  console.log(`Found ${jestCoverageFiles.length} Jest coverage file(s)`);
  jestCoverageFiles
    .map((reportFile) => {
      console.log(`  Processing: ${reportFile}`);
      // eslint-disable-next-line global-require, import/no-dynamic-require
      return require(reportFile);
    })
    .map(normalizeReport)
    .forEach((report) => coverageMap.merge(report));
} else {
  console.log('No Jest coverage files found');
}

if (e2eCoverageFile.length > 0) {
  console.log(`Found E2E coverage file: ${e2eCoverageFile[0]}`);
  e2eCoverageFile
    .map((reportFile) => {
      // eslint-disable-next-line global-require, import/no-dynamic-require
      return require(reportFile);
    })
    .map(normalizeReport)
    .forEach((report) => coverageMap.merge(report));
}

const context = createContext({ coverageMap, dir: 'coverage-frontend' });

['json', 'lcov', 'text-summary', 'clover', 'cobertura'].forEach((reporter) => {
  create(reporter, {}).execute(context);
});
